package com.utils.httpclient;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * HTTP 参数构建
 * 
 * @author JIANGLONG
 *
 */
public class HttpParamsBuilder {

	/**
	 * GET请求参数构建
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public static String getParamsBuilder(String url,
			Map<String, String> params, String encode) {
		if (null != params && !params.isEmpty()) {
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			if (!url.contains("?") || !url.endsWith("?")) {
				url += "?";
			}
			Iterator<String> it = params.keySet().iterator();
			String key = null;
			while (it.hasNext()) {
				key = it.next();
				nvps.add(new BasicNameValuePair(String.valueOf(key), String.valueOf(params.get(key))));
			}
			url += URLEncodedUtils.format(nvps, encode);
		}
		return url;
	}

	/**
	 * POST请求参数构造
	 * 
	 * @param params
	 * @return
	 */
	public static List<NameValuePair> formParamsBuilder(
			Map<String, String> params) {
		if (null != params && !params.isEmpty()) {
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			Iterator<String> it = params.keySet().iterator();
			String key = null;
			while (it.hasNext()) {
				key = it.next();
				nvps.add(new BasicNameValuePair(key, params.get(key)));
			}
			return nvps;
		}
		return null;
	}

	/**
	 * POST请求参数构造
	 * 
	 * @param params
	 * @return
	 */
	public static String jsonParamsBuilder(Map<String, String> params) {
		if (null != params && !params.isEmpty()) {
			return JSONObject.toJSONString(params);
		}
		return null;
	}

	/**
	 * MAP构建
	 * 
	 * @param obj
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> mapParamsBuilder(Object obj) {
		return JSONObject.parseObject(JSONObject.toJSONString(obj), Map.class);
	}
	
	/**
	 * 字符串转OBJECT
	 * 
	 * @param params
	 * @param clazz
	 * @return
	 */
	public static <T> T objectParamsBuilder(String params,Class<T> clazz){
		return JSONObject.parseObject(params, clazz);
	}
	
	/**
	 * 字符串转LIST
	 * 
	 * @param params
	 * @param clazz
	 * @return
	 */
	public static <T> List<T> arrayParamsBuilder(String params,Class<T> clazz){
		return JSONObject.parseArray(params, clazz);
	}
}
